import { Menu } from "antd";
import { useState } from "react";

interface Item {
    /**列表项的展示名称 */
    name: string

    /**列表项对应执行的函数 */
    action: Function
}

interface Group {
    /**菜单组的名称 */
    title: string

    /**菜单组的列表项 */
    list: Item[]
}

interface Props {
    /**菜单的菜单组列表 */
    list: Group[]

    /**默认选择的项，字符串格式：title/name */
    defaultSelected?: string[]

    /**选择的项，字符串格式：title/name */
    menuSelected?: string[]
}

const GroupMenu: React.FC<Props> = ({
    list,
    defaultSelected,
    menuSelected
}) => {
    console.debug('GroupMenu', list, menuSelected);

    const [selectedKeys, setSelectedKeys] = useState<string[]>(() => {
        return []
    })

    function handleClick(evt: any) {
        const [groupIdx, itemIdx] = evt.key.split('/');
        const group = list.find(item => item.title === groupIdx);
        if (group) {
            const item = group.list.find(_item => _item.name === itemIdx);
            if (item) {
                setSelectedKeys([`${group.title}/${item.name}`]);
                item.action();
            }
        }
    }

    return (
        <Menu
            onClick={handleClick}
            mode="inline"
            defaultSelectedKeys={defaultSelected}
            selectedKeys={selectedKeys}
        >
            {list.map(group =>
                <Menu.ItemGroup key={group.title} title={group.title}>
                    {group.list.map(item =>
                        <Menu.Item key={`${group.title}/${item.name}`}>{item.name}</Menu.Item>
                    )}
                </Menu.ItemGroup>
            )}
        </Menu>
    )
}

export default GroupMenu;